package demo2.common.util;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * 
 * 
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID    DATE            PERSON            REASON
 *  1     2017年10月28日         01367604           Create
 * ****************************************************************************
 * </pre>
 * 
 * @author 01367604
 * @version 1.0
 */
public class HibernateInvokeHandler implements InvocationHandler {

    private Session session;

    public HibernateInvokeHandler() {}

    public Session getProxyBean() {
        Session session = HibernateSessionFactory.getSession();
        this.session = session;
        Session o = (Session) Proxy.newProxyInstance(session.getClass().getClassLoader(), 
            session.getClass().getInterfaces(), this);
        return o;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Transaction transaction = session.beginTransaction();
        if (args[0] instanceof Collection) {
            List list = new ArrayList();
            list = (List) args[0];
            for (Object o : list) {
                method.invoke(session, o);
            }
        } else {
            method.invoke(session, args);
        }
        transaction.commit();
        session.close();
        return null;
    }

}
